import gevent
from gevent import monkey
monkey.patch_all()

from hashlib import md5
import traceback
import time
import json
import requests
import  models
from config import makeNewSession 
import config
from API.messageAPI import get_group_member_list

class Yqpost:
    sleepTime = 0.05
    querySize = 35

    def __init__(self):
        # check_report_banji
        self.no_list = []
        self.err_list = []

    @staticmethod
    def calcSpace(s, i:int,space:str='　'):
        return space * (i-len(str(s)))

    
    def __get_decodes(self,uname,t):
        '''
        设置验证参数
        uname: 学号
        t: 13位时间戳
        '''
        decodes = md5(f'{uname}Unifrinew{t}'.encode()).hexdigest()
        return (decodes[16:]+decodes[:16]).upper()


    def __searchReportHistory(self,schoolid,batchno=None):
        url = 'http://210.35.96.114/report/report/getMyReport'
        t = str(int(time.time()*1000))
        data = {
            "batchno": batchno,
            "usercode": f"{schoolid}"
        }
        header = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Length": str(len(json.dumps(data))),
            "Content-Type": "application/json",
            "decodes": self.__get_decodes(schoolid,t),
            "Host": "210.35.96.114",
            "Origin": "http://xgfy.sit.edu.cn",
            "Pragma": "no-cache",
            "Referer": "http://xgfy.sit.edu.cn/",
            "ts": t,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKi/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"
        }
        try:
            r = requests.post(url,headers=header,json=data, timeout=7)
            data = r.json()
            print(data)
            if data["code"] == 0:
                return data["data"]
            else: 
                return None
        except:
            traceback.print_exc()
            return None
    

    def isReportTodayById(self, schoolid:int, no_list=None, err_list=None, try_num=3,st=0.05):
        while try_num:
            data = self.__searchReportHistory(schoolid,batchno=int(time.strftime("%Y%m%d")))
            if data == None:
                pass
            elif len(data) == 1:
                if no_list:no_list.append({"uid":schoolid,"flag":True})
                return True
            elif len(data) == 0:
                if no_list:no_list.append({"uid":schoolid,"flag":False})
                return False
            try_num -= 1
            time.sleep(self.sleepTime)
        if err_list:err_list.append(str(schoolid))
        return None

    def isReportToday(self, stu:models.Student, no_list=None, err_list=None, try_num=3,st=0.05):
        while try_num:
            data = self.__searchReportHistory(stu.uid,batchno=int(time.strftime("%Y%m%d")))
            if data == None:
                pass
            elif len(data) == 1:
                return True
            elif len(data) == 0:
                if no_list:no_list.append({"uid":stu.uid, "name":stu.name, "QQ":stu.QQ, "flag":False})
                else:self.no_list.append({"uid":stu.uid, "name":stu.name, "QQ":stu.QQ, "flag":False})
                    

                # print("append no_list", stu.name, False)
                return False
            try_num -= 1
            time.sleep(self.sleepTime)
        if err_list:err_list.append({"uid":stu.uid, "name":stu.name, "QQ":stu.QQ, "flag":None})
        else:self.err_list.append({"uid":stu.uid, "name":stu.name, "QQ":stu.QQ, "flag":None})
            
        # print("append err_list", stu.name, None)
        return None

    def check_report_banji(self, banji:int, session):
        stus = session.query(models.Student).filter(models.Student.banji == banji)

        count = 0
        tasks = []
        self.no_list = []
        self.err_list = []
        for stu in stus:
            tasks.append(gevent.spawn(self.isReportToday,stu))
            count += 1
            if count % self.querySize == 0:
                # time.sleep(self.sleepTime)
                gevent.joinall(tasks)
        gevent.joinall(tasks)
        err_count = len(self.err_list)
        no_count = len(self.no_list)
        

        return dict(code=0, total=count, err_count=err_count, no_count=no_count, no_list=self.no_list, err_list=self.err_list)
    
    def check_report_banji_and_gen_msg(self, banji, group, session) -> str:
        st = time.time()
        data = self.check_report_banji(banji, session)
        if data["code"] != 0: return None

        msg = []
        msg.append(f"共{data['total']}人，{data['no_count']}未上报，{data['err_count']}查询失败\n")
        mems = get_group_member_list(group)
        # print("mems",mems)
        mems_id = set(map(lambda mem: mem["user_id"], mems))
        # 未上报
        msg.append(f"未上报名单：\n")
        for each in data["no_list"]:
            if int(each["QQ"]) in mems_id:
                msg.append(f"{each['name']}{self.calcSpace(each['name'],4)}{each['uid']}{self.calcSpace(each['uid'],11)}[CQ:at,qq={each['QQ']}]\n")
            else:
                msg.append(f"{each['name']}{self.calcSpace(each['name'],4)}{each['uid']}{self.calcSpace(each['uid'],11)}不在群中\n")
        # 查询失败
        if data["err_list"]:
            msg.append(f"查询失败名单：\n")
            for each in data["err_list"]:
                msg.append(f"{each['name']}{self.calcSpace(each['name'],4)}{each['uid']}{self.calcSpace(each['uid'],11)}\n")

        msg.append(f"耗时：{time.time()-st:.3f}s") 
        return ''.join(msg)






    






if __name__=="__main__":
    y = Yqpost()
    d = y.isReportTodayById(1810700733)
    print(d)

